package kaka.rpc
{
	import kaka.rpc.ServiceClasses.HTTPServiceInvoker;
	import kaka.rpc.ServiceClasses.RemoteObjectInvoker;
	import kaka.rpc.factory.CreateFactory;
	
	import mx.controls.Alert;

	/**
	 * 远程调用类
	 * @author kaka
	 */
	public class RemoteServiceInvoke
	{
		public static const REMOTE_OBJECT:String="remoteobject";
		
		public static const HTTPSERVICE:String="httpservice";
		
		public static const WEBSERVICES:String="webservices";
		
		private static var client:IInvoker;
		private static var invokeResponder:IInvokeResponder;
		private static var haveProcessBar:Boolean=true;
		public function RemoteServiceInvoke()
		{
		}
		/**
		 * 发送请求
		 * @author kaka
		 * @param type 调用类型(RemoteObject,HTTPService,Webservice)
		 * @param dest 远程服务名称ID
		 * @param method 方法
		 * @param args 传入参数
		 * @param resultHandlers 请求成功回调函数列表( Array )
		 * @param faultHandlers   请求失败回调函数列表( Array )
		 * @param defaultHandler 默认处理函数
		 * @param _haveProcessBar 是否显示进度条
		 */
		public static function send(type:String,dest:String,method:String,resultHandlers:Array,faultHandlers:Array,args:Array,defaultHandler:Function=null,_haveProcessBar:Boolean=true):void
		{
			haveProcessBar=_haveProcessBar;
			switch(type)
			{
				case REMOTE_OBJECT:
					client=new CreateFactory().create(RemoteObjectInvoker);      
					invokeResponder=client.invoker(dest,method,args,defaultHandler);
					addFunction(invokeResponder,resultHandlers,faultHandlers);
					break;
				case WEBSERVICES:
					client=new CreateFactory().create(RemoteObjectInvoker);      
					invokeResponder=client.invoker(dest,method,args,defaultHandler);
					addFunction(invokeResponder,resultHandlers,faultHandlers);
					break;
				case HTTPSERVICE:
					client=new CreateFactory().create(HTTPServiceInvoker);      
					invokeResponder=client.invoker(dest,method,args,defaultHandler);
					addFunction(invokeResponder,resultHandlers,faultHandlers);
					break;
				default:
					Alert.show("调用出错");
			}
		}
		//填充回调函数列表
		private static function addFunction(_invokeResponder:IInvokeResponder,resultHandlers:Array,faultHandlers:Array):void
		{
			for(var i:int=0;i<resultHandlers.length;i++)
			{
				_invokeResponder.addResultListener(resultHandlers[i]);
			}
			for(var j:int=0;j<faultHandlers.length;j++)
			{
				_invokeResponder.addFaultListener(faultHandlers[j]);
			}
		}
	} 
}